import request from '@/utils/request'
import QRCode from 'qrcode'

// 查询渠道列表
export function listChannel(query) {
  return request({
    url: '/ruoyi-activity/channel/list',
    method: 'get',
    params: query
  }).then(response => {
    const channel = response.rows;
    const promises = channel.map(channel => generateQrCode(channel));
    return Promise.all(promises).then(() => response);
  });
}

// 查询渠道详细
export function getChannel(id) {
  return request({
    url: '/ruoyi-activity/channel/' + id,
    method: 'get'
  })
}

// 新增渠道
export function addChannel(data) {
  return request({
    url: '/ruoyi-activity/channel',
    method: 'post',
    data: data
  })
}

// 修改渠道
export function updateChannel(data) {
  return request({
    url: '/ruoyi-activity/channel',
    method: 'put',
    data: data
  })
}

// 删除渠道
export function delChannel(id) {
  return request({
    url: '/ruoyi-activity/channel/' + id,
    method: 'delete'
  })
}

/**
 * 为渠道对象生成二维码
 * @param {Object} channel 渠道对象
 */
export function generateQrCode(channel) {
  const { channelCodeUrl, id } = channel;

  if (!channelCodeUrl || !id) return Promise.resolve();

  // 拼接完整带 ID 的 URL
  const fullUrl = `${channelCodeUrl}${channelCodeUrl.includes('?') ? '&' : '?'}channelId=${encodeURIComponent(id)}`;

  return QRCode.toDataURL(fullUrl)
    .then(dataUrl => {
      channel.qrCodeUrl = dataUrl; // 存储 base64 图片数据
      channel.channelCodeUrl = fullUrl; // 存储 base64 图片数据
      return channel;
    })
    .catch(err => {
      console.error('生成二维码失败:', err);
      channel.qrCodeUrl = null;
      return channel;
    });
}
